import React from 'react';
import { Component } from 'react';
import store from './../Store';
import *  as Actions from './../Actions';

export default class Counter extends Component {

    constructor(props) {
        super(props);
        this.state = {
            count: store.getState()[props.title],
            title: props.title
        }
    }

    onChange = () => {
        this.setState({
            count: store.getState()[this.state.title]
        })
    }

    onIncrement = () => {
        store.dispatch(Actions.increment(this.state.title));
    }

    onDecrement = () => {
        store.dispatch(Actions.decrement(this.state.title));
    }

    componentDidMount = () => {
        store.subscribe(this.onChange);
    }

    componentWillUnmount = () => {
        store.unsubscribe(this.onChange);
    }

    render() {
        return (
            <div>
                <p>{ this.state.title }</p>
                <button onClick={ this.onIncrement } >+</button>
                <button onClick={ this.onDecrement }>-</button>
                <p>{this.state.count}</p>
            </div>
        )
    }

}